<?php

/**
 * Configuration of a mailbox to fetch mail from
 *
 * @author tobias.vogel
 */
class Db_Mailboxes extends Common {

	protected static $tableName = TAB_MAILBOXES;
	protected static $dbFields = array(
		'id',
		'mbx_host',
		'mbx_port',
		'mbx_path',
		'mbx_user',
		'mbx_pass',
		'mbx_use_ssl',
		'mbx_last_fetch',
		'deleted'
	);

	/**
	 * @var int ID of the mailbox
	 */
	public $id;

	/**
	 * @var Db_Mailboxes
	 */
	public $object_arr;

	/**
	 * @var string Hostname of the IMAP server
	 */
	public $mbx_host;

	/**
	 * @var int The port to use
	 */
	public $mbx_port;

	/**
	 * @var string Username to access the mailbox
	 */
	public $mbx_user;

	/**
	 * @var string Password to access the mailbox
	 */
	public $mbx_pass;

	/**
	 * @var string Path in the mailbox to fetch from
	 */
	public $mbx_path;

	/**
	 * @var boolean If we should use SSL, default is false
	 */
	public $mbx_use_ssl = 0;

	/**
	 * @var int Timestamp of the last fetch
	 */
	public $mbx_last_fetch = 0;

	function __construct($value = NULL, $fieldName = NULL) {
		parent::__construct($value, $fieldName);
	}

	public static function build($host, $user, $password, $path = 'INBOX', $useSsl = false) {
		$mbox = new Db_Mailboxes();

		$mbox->mbx_host = $host;
		$mbox->mbx_user = $user;
		$mbox->mbx_pass = $password;
		$mbox->mbx_path = $path;
		$mbox->mbx_use_ssl = (bool) $useSsl;
		$mbox->mbx_port = $mbox->mbx_use_ssl ? 993 : 143;

		return $mbox;
	}

	/**
	 * Returns a DSN for connection via imap extension of PHP 
	 * 
	 * @return string Connectiopn string
	 */
	public function getDsn() {
		$flags = '/imap';
		$flags .= ($this->mbx_use_ssl) ? '/ssl/novalidate-cert' : '';
		$dsn = '{' . $this->mbx_host . ':' . $this->mbx_port . $flags . '}' . $this->mbx_path;
		return $dsn;
	}

}
